<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Warehouse extends AdminController
{
    public $_validation = null;

    function __construct()
    {
        parent::__construct();
        $this->load->model('MShop');
        $this->load->model('MAdmin');
        $allShops = $this->MShop->getAllShopsTrue();
        $allPurchaser = $this->MAdmin->getAllPurchaser();
        $this->load->model('MStorageRecord');
        $this->_validation = Array(
            array('field' => 'order_no', 'label' => '订单号', 'rules' => 'trim|max_length[255]')
        , array('field' => 'quantity', 'label' => '数量', 'rules' => 'integer')
        , array('field' => 'amount', 'label' => '总价', 'rules' => '')
        , array('field' => 'related_person', 'label' => '责任人', 'rules' => '')
        , array('field' => 'type', 'label' => '出入库', 'rules' => '')
        , array('field' => 'type_mark', 'label' => '出入库类型', 'rules' => 'required|integer')
        , array('field' => 'warehousing', 'label' => '货物批次', 'rules' => '')
        , array('field' => 'shop_id', 'label' => '所属账户', 'rules' => 'required')
        , array('field' => 'status', 'label' => '状态', 'rules' => 'integer')
        , array('field' => 'remark', 'label' => '备注', 'rules' => '')
        , array('field' => 'location', 'label' => '仓库', 'rules' => '')
        , array('field' => 'area', 'label' => '仓库存储区', 'rules' => '')
        , array('field' => 'purchase_time', 'label' => '采购时间', 'rules' => 'required')
        );
        $this->assign('allShops', $allShops);
        $this->assign('allPurchaser', $allPurchaser);
    }

    public function index()
    {
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->formfilter->addFilter('r.order_no', 'like');
        $this->formfilter->addFilter('r.shipping_no', 'like');
        $this->formfilter->addFilter('p.product_name', 'like');
        $this->formfilter->addFilter('r.shop_id', 'where');
        $this->formfilter->addFilter('r.product_id', 'where');
        $this->formfilter->addFilter('r.warehousing', 'where');
        $this->formfilter->addFilter('r.type_mark', 'where');
        $this->formfilter->addFilter('r.status', 'where');
        $this->formfilter->addFilter('w.location', 'where');
        $this->formfilter->addFilter('r.purchaser_id', 'where');

        if ($begintime = filterValue('record_create_time_begin')) {
            $this->formfilter->addFilter('record_create_time_begin', 'where', array('r.create_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('record_create_time_end')) {
            $this->formfilter->addFilter('record_create_time_end', 'where', array('r.create_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        $number_perpage = filterValue('record_number_perpage');
        $order_type = filterValue('record_order_type');

        $total_number = $this->MStorageRecord->getCount();
        $limit = $this->pagination($total_number, '', $number_perpage);
        $list = $this->MStorageRecord->getList($limit, $order_type);

        $this->load->model('MStorageProduct');
        $allProducts = $this->MStorageProduct->getAllProducts();
        $this->assign('allProducts', $allProducts);
        $this->assign('list', $list);
        $this->assign('allProducts', $allProducts);
        $this->layout();
    }

    /**
     * 添加入库记录
     * @param $product_id
     */
    public function add_in($product_id)
    {
        $obj = $this->MStorageRecord->createVo();
        $obj->purchaser_id = $this->_user->id;
        $obj->product_id = $product_id;
        $input_data = $this->input->post();

        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->db->trans_start();
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            $newObj->purchase_time = strtotime($this->input->post('purchase_time'));
            if ($this->MStorageRecord->add($newObj)) {
                if ($newObj->status == 1) {
                    $this->load->model('MStorageWarehouse');
                    $warehousing_his = $this->MStorageWarehouse->getOne(['product_id' => $product_id, 'warehousing' => $newObj->warehousing]);
                    if ($warehousing_his) {
                        $warehousing_his->left_number = $warehousing_his->left_number + $newObj->quantity;
                        $warehousing_his->origin_number = $warehousing_his->origin_number + $newObj->quantity;
                        if (!$this->MStorageWarehouse->update($warehousing_his)) {
                            $this->db->_trans_status = FALSE;
                        }
                    } else {
                        $houseData = [
                            'location' => $input_data['location'],
                            'area' => $input_data['area'],
                            'shop_id' => $input_data['shop_id'],
                            'product_id' => $product_id,
                            'warehousing' => $input_data['warehousing'],
                            'origin_number' => $input_data['quantity'],
                            'left_number' => $input_data['quantity'],
                            'purchaser_id' => $this->_user->id,
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                        if (!$this->MStorageWarehouse->add((Object)$houseData)) {
                            $this->db->_trans_status = FALSE;
                        }
                    }
                }
            } else {
                $this->db->_trans_status = FALSE;

            }

            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                successAndRedirect('添加记录成功');
            } else {
                errorAndRedirect('添加失败');
            }
        }else{
            $this->assign('error',$this->form_validation->error_string());
        }

        $warehousing = date('Ymdhi', time());
        $this->assign('obj', $obj);
        $this->assign('warehousing', $warehousing);
        $this->layout('in');
    }

    /**
     * 添加出库记录
     * @param $product_id
     */
    function add_out($product_id)
    {
        $this->load->model('MStorageWarehouse');
        $this->load->library('form_validation');
        $this->load->model('MStorageProduct');
        //类型为出库，验证该产品是否有库存
        if (!isset($product_id)) {
            errorAndRedirect('商品信息有误！');
        }
        $counts = $this->MStorageWarehouse->getStorage($product_id);
        if (!$counts || !$counts->left_nums) {
            errorAndRedirect('此商品暂无库存，不可出库！', '/storage/product');
        }
        $housings = $this->MStorageWarehouse->getAll(['product_id' => $product_id, 'left_number >' => 0]);

        //获取产品单价
        $product = $this->MStorageProduct->getById($product_id);
        $obj = $this->MStorageRecord->createVo();
        $this->form_validation->set_rules($this->_validation);
        if ($this->form_validation->run() == TRUE) {
            $this->db->trans_start();
            $input_data = $this->input->post();

            //未选择批次
            if (!isset($input_data['housing'])) {
                errorAndRedirect('请选择出库的批次！', 'storage/product');
            }
            $this->load->helper('populate');
            foreach ($input_data['housing'] as $k => $v) {
                if ($v) {
                    $warehouse = $this->MStorageWarehouse->getOne(['product_id' => $product_id, 'warehousing' => $k]);
                    if ($warehouse->left_number < $v) {
                        errorAndRedirect('批次' . $k . '货物超出可出库最大数量！');
                    }

                    $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
                    $newObj->purchase_time = strtotime($this->input->post('purchase_time'));
                    $newObj->purchaser_id = $this->_user->id;
                    $newObj->product_id = $product_id;
                    $newObj->warehousing = $k;
                    $newObj->quantity = $v;
                    $newObj->amount = $input_data['amount'][$k];

                    if ($this->MStorageRecord->add($newObj)) {
                        $warehouse->left_number = $warehouse->left_number - $v;
                        if (!$this->MStorageWarehouse->update($warehouse)) {
                            $this->db->_trans_status = FALSE;
                        };
                    } else {
                        $this->db->_trans_status = FALSE;
                    }
                }

            }

            if ($this->db->trans_status() !== FALSE) {
                $this->db->trans_complete();
                successAndRedirect('添加记录成功');
            } else {
                errorAndRedirect('添加失败');
            }
        }
        $allProduct = $this->MStorageProduct->getAllProducts();
        $warehousing = date('Ymdhi', time());
        $this->assign('obj', $obj);
        $this->assign('price', $product->price);
        $this->assign('warehousing', $warehousing);
        $this->assign('housings', $housings);
        $this->assign('allProduct', $allProduct);
        $this->layout('out');
    }

    function edit($id)
    {
        $this->db->trans_start();
        if ($this->input->post('is_deliver')){
            $redirect = site_url('storage/shipping/deliver');
        }else{
            $redirect = site_url('storage/warehouse/index');
        }

        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MStorageRecord->getOne(['id' => $id]);
        if (!$obj) {
            errorAndRedirect('未找到定义！',$redirect);
        }
        $this->editObj = $obj;
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);
        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            $newObj->purchase_time = strtotime($newObj->purchase_time);

            if (!$this->MStorageRecord->update($newObj)) {
                $this->db->_trans_status = false;
            }else{
                //写入操作记录
                $content = '';
                foreach ($newObj as $key =>$value){
                    if ($key == 'amount' || $key == 'purchase_time'){
                        $newObj->$key = (float)$newObj->$key;
                        $obj->$key = (float)$obj->$key;
                    }

                    //给数字赋值
                    if ($key == 'shop_id'){
                        $this->load->model('MShop');
                        $allShops = $this->MShop->getAllShopsTrue();
                        $obj->shop_id = $allShops[$obj->shop_id];
                        $newObj->shop_id = $allShops[$newObj->shop_id];
                    }

                    if($key == 'type_mark'){
                        $newObj->type_mark = IOSS_StaticConfig::getShippingType($newObj->type_mark);
                        $obj->type_mark = IOSS_StaticConfig::getShippingType($obj->type_mark);
                    }

                    if($key == 'purchase_time'){
                        $newObj->purchase_time = date('Y-m-d',$newObj->purchase_time);
                        $obj->purchase_time = date('Y-m-d',$obj->purchase_time);
                    }

                    if ($newObj->$key !== $obj->$key && $key !== 'update_time'){
                        $content .= ' '.IOSS_StaticConfig::translateLogField($key).' 由 '.$obj->$key.' 改为 '.$newObj->$key.';';
                    }
                }

                $msg = '修改成功！';
                //编辑状态为成功的进出库记录时，需要更新库存数量
                if ($newObj->status == 1){
                    $this->load->model('MStorageEditHistory');

                    //入库
                    $this->load->model('MStorageWarehouse');
                    $warehouse = $this->MStorageWarehouse->getOne(['product_id' => $newObj->product_id,'warehousing' =>$newObj->warehousing]);

                    if ($warehouse->location !== $this->input->post('location')){
                        $content .= ' 仓库 由 '.($warehouse->location==1?'合肥':'深圳').' 改为 '.($this->input->post('location')==1?'合肥':'深圳').';';
                    }

                    if ($warehouse->area !== $this->input->post('area')){
                        $content .= ' 所在区 由 '.IOSS_StaticConfig::getShippingBlock($warehouse->area).' 改为 '.IOSS_StaticConfig::getShippingBlock($this->input->post('area')).';';
                    }

                    $warehouse->location = $this->input->post('location');
                    $warehouse->area = $this->input->post('area');
                    if ($newObj->type){
                        $out_num = $warehouse->origin_number -$warehouse->left_number;
                        if ($out_num > $newObj->quantity){
                            $this->db->_trans_status = false;
                            $msg = '修改失败，修改数量不可小于已出库数量！';
                        }else{
                            if ($obj->quantity == $warehouse->origin_number){
                                $warehouse->origin_number = $newObj->quantity;
                                $warehouse->left_number = $newObj->quantity - $out_num;
                            }else{
                                $warehouse->origin_number = $warehouse->origin_number + ($newObj->quantity - $obj->quantity);
                                $warehouse->left_number = $warehouse->left_number + ($newObj->quantity - $obj->quantity);
                            }
                            if (!$this->MStorageWarehouse->update($warehouse)){
                                $this->db->_trans_status = false;
                                $msg = '修改失败！';
                            }
                        }
                    }else{
                        //出库
                        if ($newObj->quantity > ($obj->quantity + $warehouse->left_number) ){
                            $this->db->_trans_status = false;
                            $msg = '修改失败，修改数量不可超出可出库数量！';
                        }else{
                            $desc_num = $newObj->quantity - $obj->quantity;
                            $warehouse->left_number = $warehouse->left_number - $desc_num;
                            if (!$this->MStorageWarehouse->update($warehouse)){
                                $this->db->_trans_status = false;
                                $msg = '修改失败！';
                            }
                        }
                    }
                }
                if ($content){
                    $this->editLog($this->_user->id,$id,$this->_thisModule.$this->_thisController.'/'.$this->_thisMethod,$content);
                }
            }
        }else{
            $this->db->trans_complete();
            errorAndRedirect($this->form_validation->error_string(),$redirect);
        }
        $this->db->trans_complete();
        if ($this->db->_trans_status !== false){
            successAndRedirect(l('edit_success'),$redirect);
        }else{
            errorAndRedirect($msg,$redirect);
        }
    }

    function view($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $this->load->model('MTaskApplyNum');
        $obj = $this->MTask->getOne(Array('id' => $id));
        $apply = $this->MTaskApplyNum->getOne(['operator_id' => $this->_user->id, 'task_id' => $id]);
        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }
        //该任务的所有操作记录
        $this->load->model('MTaskOperate');
        $allOperatesOfTaskId = $this->MTaskOperate->getAll(array('task_id =' => $id));
        $distinctOrderNoOperates = $this->MTaskOperate->getDistinctOrderNoOperates($id, $this->_user->id);

        $allReviewsAdmin = $this->MAdmin->getAllReviewsAdmin();//所有测评人
        if ($apply && (int)$distinctOrderNoOperates->operate_numbers < (int)($apply->apply_sale_num + $apply->apply_comment_num)) {
            $obj->is_apply = true;
        } else {
            $obj->is_apply = false;
        }

        $this->assign('obj', $obj);
        $this->assign('allOperatesOfTaskId', $allOperatesOfTaskId);
        $this->assign('allReviewsAdmin', $allReviewsAdmin);
        $this->layout('view.tpl');
    }

    function delete($id, $update_time)
    {
        if (!is_numeric($id) || !is_numeric($update_time)) {
            show_error(l('id_not_null'));
        }
        if (!$this->MTask->delete($id, $update_time)) {
            errorAndRedirect(l('data_fail'));
        }
        successAndRedirect(l('delete_success'));
    }

    function ajaxWarehousing()
    {
        $data = $this->input->post();
        $product_id = $data['product_id'];

        $this->load->model('MStorageWarehouse');
        $list = $this->MStorageWarehouse->getHousing($product_id);
        if (count($list)) {
            exit(json_encode([
                'success' => true,
                'msg' => '获取成功',
                'data' => $list
            ]));
        } else {
            exit(json_encode([
                'success' => false,
                'msg' => '暂无数据'
            ]));
        }
    }

    function in_success()
    {
        $data = $this->input->post();
        if (!isset($data['id'])) {
            exit(json_encode([
                'success' => 0,
                'msg' => '未定义的记录！'
            ]));
        }
        $record = $this->MStorageRecord->getOne(['id' => $data['id']]);
        $record->status = 1;
        $this->db->trans_start();

        if ($this->MStorageRecord->update($record)) {

            $this->load->model('MStorageWarehouse');
            $warehousing_his = $this->MStorageWarehouse->getOne(['product_id' => $record->product_id, 'warehousing' => $record->warehousing]);

            if ($warehousing_his) {
                $warehousing_his->left_number = $warehousing_his->left_number + $record->quantity;
                $warehousing_his->origin_number = $warehousing_his->origin_number + $record->quantity;
                if (!$this->MStorageWarehouse->update($warehousing_his)) {
                    $this->db->_trans_status = FALSE;
                }
                $in_type = 'merge';
            } else {
                $houseData = [
                    'location' => $data['location'],
                    'area' => $data['area'],
                    'shop_id' => $record->shop_id,
                    'product_id' => $record->product_id,
                    'warehousing' => $record->warehousing,
                    'origin_number' => $record->quantity,
                    'left_number' => $record->quantity,
                    'purchaser_id' => $this->_user->id,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                if (!$this->MStorageWarehouse->add((Object)$houseData)) {
                    $this->db->_trans_status = FALSE;
                }
                $in_type = 'new';
            }

        } else {
            $this->db->_trans_status = FALSE;
        }
        if ($this->db->_trans_status) {
            $this->db->trans_complete();
            exit(json_encode([
                'success' => 1,
                'msg' => '入库成功！',
                'type' => $in_type
            ]));
        } else {
            exit(json_encode([
                'success' => 0,
                'msg' => '入库失败！',
            ]));
        }
    }

    /**
     * 入库作废
     * @param $id
     */
    function in_fail($id)
    {
        $this->db->trans_start();
        $detail = $this->MStorageRecord->getOne(['id' => $id]);
        $detail->status = 0;
        if ($this->MStorageRecord->update($detail)) {
            $this->load->model('MStorageWarehouse');
            $warehouse = $this->MStorageWarehouse->getOne(['product_id' => $detail->product_id, 'warehousing' => $detail->warehousing]);

            if (!$warehouse) {
                $this->db->_trans_status = FALSE;
                errorAndRedirect('无该批次记录！');
            } else {
                $outRecord = $this->MStorageRecord->getOne(['product_id' => $detail->product_id, 'warehousing' => $detail->warehousing, 'type' => 0]);
                if ($outRecord) {
                    errorAndRedirect('该批次已有出库记录，不可作废！');
                } else {
                    if ($detail->quantity < $warehouse->origin_number) {

                        $warehouse->left_number = $warehouse->left_number - $detail->quantity;
                        $warehouse->origin_number = $warehouse->origin_number - $detail->quantity;
                        if (!$this->MStorageWarehouse->update($warehouse)) {
                            $this->db->_trans_status = FALSE;
                        }
                    } else {
                        if (!$this->MStorageWarehouse->delete($warehouse->id,$warehouse->update_time)) {
                            $this->db->_trans_status = FALSE;
                        }
                    }
                }

            }
        } else {
            $this->db->_trans_status = FALSE;
        }
        $this->db->trans_complete();
        if ($this->db->_trans_status !== FALSE) {
            successAndRedirect('作废成功，已清除该批次信息！');
        } else {
            errorAndRedirect('操作失败！');
        }
    }

    function out_fail($id)
    {
        $this->db->trans_start();
        $detail = $this->MStorageRecord->getOne(['id' => $id]);
        $detail->status = 0;
        if ($this->MStorageRecord->update($detail)) {
            $this->load->model('MStorageWarehouse');
            $warehouse = $this->MStorageWarehouse->getOne(['product_id' => $detail->product_id, 'warehousing' => $detail->warehousing]);
            if (!$warehouse) {
                $this->db->_trans_status = FALSE;
                errorAndRedirect('无该批次记录！');
            } else {
                $warehouse->left_number = $warehouse->left_number + $detail->quantity;
                if (!$this->MStorageWarehouse->update($warehouse)) {
                    $this->db->_trans_status = FALSE;
                }
            }
        } else {
            $this->db->_trans_status = FALSE;
        }
        $this->db->trans_complete();
        if ($this->db->_trans_status !== FALSE) {
            successAndRedirect('作废成功，已还原该批次可出库数量！');
        } else {
            errorAndRedirect('操作失败！');
        }
    }

    public function ajaxDetail(){
        $detail = $this->MStorageRecord->getById($this->input->post('id'));
        $detail->purchase_time = date('Y-m-d',$detail->purchase_time);
        exit(json_encode($detail));
    }

    public function ajaxHis(){
        $this->load->model('MStorageEditHistory');
        $data = $this->input->post();
        $list = $this->MStorageEditHistory->getAll(['route' => $data['route'], 'effect_id' => $data['id']]);
        $this->load->model('MAdmin');
        $allPurchaser = $this->MAdmin->getAllPurchaser();
        if (count($list)){
            foreach ($list as $v){
                $v->user_name = $allPurchaser[$v->user_id];
                $v->create_time = date('Y-m-d H:i',$v->create_time);
            }
        }
        exit(json_encode($list));
    }
}
